package org.fly.controller.admin;

import org.fly.bean.User;
import org.fly.bean.common.BusinessException;
import org.fly.contants.WebConstant;
import org.fly.controller.AbstractController;
import org.fly.service.UserService;
import org.fly.utils.CookieUtil;
import org.fly.utils.JsonUtils;
import org.fly.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author  fly
 */
@Controller
@RequestMapping("/admin/")
public class AdminLoginController extends AbstractController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "loginOn", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login(String account,String password,
                        HttpServletRequest request,
                        HttpServletResponse response){
        User user = null;
        try{
            user =  userService.login(account,password);
            CookieUtil.setLoginCookie(response,user,"");
        }catch (BusinessException e){
            return toExceptionString(e);

        }
        return JsonUtils.encode(createDataTip(user));
    }
    @RequestMapping(value = "logout", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        for(Cookie cookie :request.getCookies()){
            if(WebConstant.cookie_token.equals(cookie.getName())){
                userService.logout(cookie.getValue());
            }
        }
        return toJSONString(SUCCESS);
    }
    @RequestMapping(value = "updatePassword", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String updatePassword(String oldPassword,String newPassword, HttpServletRequest request) throws IOException {
        User user = (User) UserContext.getUser();
        try{
            userService.updatePassword(user.getId(),oldPassword,newPassword);
        }catch (BusinessException e){
            return toExceptionString(e);
        }
        return toJSONString(SUCCESS);
    }
}
